package com.br.fiscalizacao.web;

import com.br.fiscalizacao.domain.Documento;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.runner.Request;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestScope;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

@RequestMapping("/documentoes")
@Controller
@RooWebScaffold(path = "documentoes", formBackingObject = Documento.class)
@RooWebFinder
public class DocumentoController {

    private static final Log log = LogFactory.getLog(DocumentoController.class);

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }

    @RequestMapping(value = "savedoc", method = RequestMethod.POST)
    public String createdoc(@Valid Documento document, BindingResult result, Model model, @RequestParam("content") MultipartFile content, HttpServletRequest request) {
        document.setContentType(content.getContentType());
        document.setFilename(content.getOriginalFilename());
        log.debug("Document: ");
        log.debug("Name: " + content.getOriginalFilename());
        log.debug("Type: " + content.getContentType());
        log.debug("Numdocumento " + document.getNum_documento());
        log.debug("Tipodocumento:" + document.getTipo_documento());
        log.debug("Datadocumento:" + document.getData_documento());
        log.debug("Assunto:" + document.getAssunto());
        log.debug("Responsavel:" + document.getResponsavel());
        log.debug("Interesssado: " + document.getInteressado());
        log.debug("Situacaodocumento:" + document.getSituacao_documento());
        log.debug("Situacao" + document.getRequisicoes());
        log.debug("Nomearquivo" + document.getFilename());
        if (result.hasErrors()) {
            model.addAttribute("documento", document);
            return "documentoes/create";
        }
        document.persist();
        return "redirect:/documentoes?page=1&size=10" + encodeUrlPathSegment(document.getId().toString(), request);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model model) {
        Documento doc = Documento.findDocumento(id);
        doc.setUrl("http://localhost:8080/fiscalizacao-v1.1/documentoes/showdoc/" + id);
        model.addAttribute("documento", Documento.findDocumento(id));
        model.addAttribute("itemId", id);
        return "documentoes/show";
    }

    @RequestMapping(value = "/showdoc/{id}", method = RequestMethod.GET)
    public String showdoc(@PathVariable("id") Long id, HttpServletResponse response, Model model) {
        Documento doc = Documento.findDocumento(id);
        try {
            response.setHeader("Content-Disposition", "inline;filename=\"" + doc.getFilename() + "\"");
            OutputStream out = response.getOutputStream();
            response.setContentType(doc.getContentType());
            IOUtils.copy(new ByteArrayInputStream(doc.getContent()), out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        Documento document = Documento.findDocumento(id);
        document.setUrl("http://localhost:8080/fiscalizacao-v1.1/documentoes/showdoc/" + id);
        model.addAttribute("documento", document);
        return "documentoes/update";
    }
}
